function DojoLib(){	
}
/*******************************************************************************
 * script for load script
 ******************************************************************************/
DojoLib.prototype.loadJsWithHandleFunc = function(url, jsLoadCompleteHandleFunc) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    
    if (script.readyState) { // IE
        script.onreadystatechange = function() {
            if (script.readyState == "loaded"
                || script.readyState == "complete") {
                script.onreadystatechange = null;
                jsLoadCompleteHandleFunc();
            }
        };
    } else { // Others
        script.onload = function() {
            jsLoadCompleteHandleFunc();
        };
    }

    script.src = url;

    /***************************************************************************
	 * beware function duplicate on head
	 **************************************************************************/
    document.getElementsByTagName("head")[0].appendChild(script);
//alert(document.getElementsByTagName("head")[0].innerHTML);
};
DojoLib.prototype.loadJs = function (url) {
    var script = document.createElement("script");
    script.type = "text/javascript";

    if (script.readyState) { // IE
        script.onreadystatechange = function() {
            if (script.readyState == "loaded"
                || script.readyState == "complete") {
                script.onreadystatechange = null;
            //callback(script);
            }
        };
    } else { // Others
        script.onload = function() {
        };
    }

    script.src = url;

    /***************************************************************************
	 * beware function duplicate on head
	 **************************************************************************/
    document.getElementsByTagName("head")[0].appendChild(script);
//alert(document.getElementsByTagName("head")[0].innerHTML);
};

/*******************************************************************************
 * bind store to grid
 ******************************************************************************/
DojoLib.prototype.bindGridStore = function (url, jsonParam, gridId){
    this.postJsonStandby(url, jsonParam, function(result){
        var grid = dijit.byId(gridId);
        //grid.store = new dojo.data.ItemFileReadStore({data:result});
        grid.store = new dojox.data.AndOrReadStore({
            data:result
        });
        grid._refresh();
        grid.selection.clear();
        grid.startup();
    },gridId);	
};


/*******************************************************************************
 * bind store to combo
 ******************************************************************************/
DojoLib.prototype.bindComboStore = function (url, jsonParam, comboId){
    this.postJson(url, jsonParam, function(result){
        var combo = dijit.byId(comboId);
        var store = new dojox.data.AndOrReadStore({
            data:result
        });
        combo.set('store', store);
        combo.startup();
    });	
};
DojoLib.prototype.bindComboStoreWithValue = function (url, jsonParam, comboId, value){
    this.postJson(url, jsonParam, function(result){
        var combo = dijit.byId(comboId);
        var store = new dojox.data.AndOrReadStore({
            data:result
        });
        combo.set('store', store);
        combo.set('value', value);
        combo.startup();
    });	
};
DojoLib.prototype.bindComboStoreEmpty = function(comboId) {
    var combo = dijit.byId(comboId);
    var store = new dojox.data.AndOrReadStore({
        data : {
            "items" : []
        }
    });
    combo.set('store', store);
    combo.set('value', "");
    combo.startup();
};
DojoLib.prototype.bindComboStoreWithValueAndFunc = function (url, jsonParam, comboId, value, LoadCompleteHandle){
    this.postJson(url, jsonParam, function(result){
        var combo = dijit.byId(comboId);
        var store = new dojox.data.AndOrReadStore({
            data:result
        });
        combo.set('store', store);
        combo.set('value', value);
        combo.startup();
        LoadCompleteHandle();
    });	
};

/*******************************************************************************
 * easy post json to url with handle function
 ******************************************************************************/
DojoLib.prototype.postJson = function (url, data, handleLoad, handleBusinessErrorFunc) {
    var xhrArgs = {
        url : url,
        urlPreventCache : true, 
        clearOnClose : true,
        postData : dojo.toJson(data),
        handleAs : "json",
        headers : {
             'X-Requested-With':null,"Content-Type" : "application/json; charset=utf-8"
        },
        load : function(res){
            DojoLib.handlePostError(url, res, handleLoad, handleBusinessErrorFunc);
        },
        error : function(error) {
            //alert(error);
            console.error(error);
        }
    };
    dojo.rawXhrPost(xhrArgs);
};

DojoLib.prototype.newStandbyWidget = function(targetName) {
    var standbyMsgBox = new dojox.widget.Standby({
        target: targetName, 
        text:"กรุณารอสักครู่ ระบบกำลังติดต่อฐานข้อมูล", 
        color:"#DDDDDD"
    });
    document.body.appendChild(standbyMsgBox.domNode);
    standbyMsgBox.startup();
    return standbyMsgBox;
}

/*******************************************************************************
 * easy post json to url with handle function & Standby Widget
 ******************************************************************************/
DojoLib.prototype.postJsonStandby = function (url, data, handleLoad, targetId) {
    var standbyMsgBox = newStandbyWidget(targetId);
    //	console.debug(targetId+" standby.show()");
    standbyMsgBox.show();
    var xhrArgs = {
        url : url,
        postData : dojo.toJson(data),
        handleAs : "json",
        headers : {
             'X-Requested-With':null,"Content-Type" : "application/json; charset=utf-8"
        },
        load : function(res){
            DojoLib.handlePostError(url, res, handleLoad);
            standbyMsgBox.hide();
        },
        error : function(error) {
            standbyMsgBox.hide();
            //            	console.debug(targetId+" standby.hide()");
            //                alert(error);
            console.error(error);
        }
    };
    dojo.rawXhrPost(xhrArgs);
};
/*******************************************************************************
 * handle post error
 ******************************************************************************/
DojoLib.handlePostError = function (url, data, chainHandle, handleBusinessErrorFunc){
    var resVal = false;
    if(data != null && data.error == 'session timeout'){
        //alert('session timeout for url ' + url); bug 2815
        console.error('session timeout for url ' + url);
        document.location = data.url;
    }else if(data != null && data.CallStatus == 'F'){
        //alert(data.CallStatusMessage);
        console.error(data.CallStatusMessage);
        //alertBox('เกิดข้อผิดพลาด โปรดติดต่อผู้ดูแลระบบ');
        alertBoxWithFunction('เกิดข้อผิดพลาด โปรดติดต่อผู้ดูแลระบบ', function(){
            try{
                handleBusinessErrorFunc(data);
            }catch(err){
            //console.error(err);
            }
        });
    }else if(data != null && data.businessExceptionCode != null){
        console.error(data.businessMessage);
        alertBoxWithFunction(data.businessMessage, function(){
            try{
                handleBusinessErrorFunc(data);
            }catch(err){
            //console.error(err);
            }
        });
    }else{
        if(data == null){
            data = '';
        }	
        try{
            chainHandle(data);
        }catch(err){
            console.error(err);
        }
    }
};

/*******************************************************************************
 * get value from input for json
 ******************************************************************************/
DojoLib.prototype.encodeForJson = function (val){
    val = val.replace(/"/g, "&dquote;");
    val = val.replace(/\\/g, "&bslash;");
    return val;
};
DojoLib.prototype.getValForJson = function (elementId){
    if(!dijit.byId(elementId)){
        //        alert(elementId + ' not found');
        console.error(elementId + ' not found');
        return null;
    }
    var val = dijit.byId(elementId).get('value');
    val = this.encodeForJson(val);
    return val;
};
DojoLib.prototype.getValForJsonStr = function (elementId){
    return this.getDataForJsonStr(elementId,'value');
};
DojoLib.prototype.getDataForJsonStr = function (elementId,dataName){
    if(!dijit.byId(elementId)){
        console.error(elementId + ' not found');
        return "";
    }
    var val = dijit.byId(elementId).get(dataName);
    if(val==null){
        console.error(elementId + '.value is null');
        return "";
    }
    val = this.encodeForJson(val);
    return val;
};
DojoLib.prototype.getValForJsonInt = function (elementId){
    if(!dijit.byId(elementId)){
        console.error(elementId + ' not found');
        return 0;
    }
    var strVal = dijit.byId(elementId).get('value');
    if(strVal==null || strVal==""){
        console.error(elementId + '.value is null or empty');
        return 0;
    }
    var val = +strVal;
    return val;
};
DojoLib.prototype.getDateForJson = function (elementId){
    var element = dijit.byId(elementId);
    if(!element){
        //        alert('elementId = ' + elementId + ' is not define');
        console.error('elementId = ' + elementId + ' is not define');
        return '';
    }
    var dateVal = dijit.byId(elementId).get('value');
    if(dateVal ==undefined || dateVal == ''){
        return '';
    }
    var isoFormat = dojo.date.stamp.toISOString(dateVal, {
        selector: 'date'
    });
    return isoFormat;
};
DojoLib.prototype.getTimeForJson = function (elementId){
    var element = dijit.byId(elementId);
    if(!element){
        //        alert('elementId = ' + elementId + ' is not define');
        console.error('elementId = ' + elementId + ' is not define');
        return '';
    }
    var dateVal = dijit.byId(elementId).get('value');
    if(dateVal ==undefined || dateVal == ''){
        return '';
    }
    var isoFormat = dojo.date.stamp.toISOString(dateVal, {
        selector: 'time'
    });
    return isoFormat.substring(1, isoFormat.length);
};

/*******************************************************************************
 * support filterGridByAttributesAndQueryStr
 ******************************************************************************/
DojoLib.prototype.getQueryByAttributesAndQueryStr = function (attributes, queryStr) {
    var query = '';
    for ( var i = 0; i < attributes.length; i++) {
        if (i > 0) {
            query += ' || ';
        }
        query += '' + attributes[i] + ':"*' + queryStr + '*"';
    }
    return query;
};

DojoLib.prototype.getQueryString = function (attributes, queryStr) {
    var query = '';
    for ( var i = 0; i < attributes.length; i++) {
        if (i > 0) {
            query += ' || ';
        }
        query += '' + attributes[i] + ':"*' + queryStr + '*"';
    }
    return "{"+query+"}";
};

/*******************************************************************************
 * put store from outside
 ******************************************************************************/
DojoLib.prototype.filterGridByAttributesAndQueryStr = function (attributes, queryStr, gridId, store,
    fetchHandleFunc) {
    queryStr = this.getQueryByAttributesAndQueryStr(attributes, queryStr);

    var grid = dijit.byId(gridId);
    store.fetch({
        query : queryStr,
        onComplete : function(items, request) {
            var myFilter = {};
            myFilter.items = items;

            var newSearchResult = new dojo.data.ItemFileReadStore({
                data : myFilter
            });
            grid.setStore(newSearchResult);

            fetchHandleFunc(items, request);
        }
    });
};

DojoLib.prototype.filterGridByTextbox = function (attributes, filterTxtId, gridId) {
    var queryStr = "{"+this.getQueryByAttributesAndQueryStr(attributes, dijit.byId(filterTxtId).get("displayedValue"))+"}";
    //    console.debug('queryStr: '+queryStr);
    dijit.byId(gridId).setQuery(queryStr);
    dijit.byId(filterTxtId).focus();
};

DojoLib.prototype.filterGridByTwoTextbox = function (attributes1, filterTxtId1, attributes2, filterTxtId2, gridId) {
    var queryStr = "{(";
    queryStr += this.getQueryByAttributesAndQueryStr(attributes1, dijit.byId(filterTxtId1).get("displayedValue"));
    queryStr += ") AND (";
    queryStr += this.getQueryByAttributesAndQueryStr(attributes2, dijit.byId(filterTxtId2).get("displayedValue"));
    queryStr += ")}";
    //    console.debug('queryStr: '+queryStr);
    dijit.byId(gridId).setQuery(queryStr);
    dijit.byId(filterTxtId1).focus();
};
	
/*******************************************************************************
 * replace key with display (formatter)
 ******************************************************************************/
/**
 * jsonUrl คือ url ของ json store <br/>
 * itemKeyField คือ field ใน json store ที่จะใช้จับคู่กับ key <br/>
 * itemValField คือ field ใน json store ที่จะ replace key นั้น <br/>
 * key คือ key ที่จะถุก replace ด้วย val ที่มีความเกี่ยวข้องกัน <br/>
 * handleFunc คือ function ที่จะนำ val ไปทำอะไรต่อไป <br/>
 * <br/>
 * by First Chief
 */
DojoLib.prototype.replaceKeyWithJson = function (jsonUrl, itemKeyField, itemValField, key, handleFunc){
    this.postJson(jsonUrl, '', function(res){
        var items = res.items;
        var result = null;
        for(var i=0;i<items.length;i++){
            if(items[i][itemKeyField] != key){
                continue;
            }
            result = items[i][itemValField];
            break;
        }
        handleFunc(result);
    });  
};

/*********************************************************************************************************
 * cpb-lib by First Chief
 * dev for his project
 * 27-09-2012
 ********************************************************************************************************/